import React, {useState, useEffect, useRef } from "react";
import {get, trim} from "lodash";
import {Modal, Form, Input, Checkbox, Button, Col, Space, Table, ConfigProvider } from "antd/lib";
import zhCN from 'antd/es/locale/zh_CN';
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import {UserProfile} from "@/components/proptypes";
import notification from "@/services/notification";
import {currentUser} from "@/services/auth";
import Customer from "@/services/customer";
import {StarOutlined, UploadOutlined, SearchOutlined } from "@ant-design/icons";
import Uploads from "@/services/uploads";
import Attaches from "@/services/attaches";
import Upload from "antd/lib/upload";
import ContractApply from "@/services/contractapply";
import moment from "moment";
import { Query } from "@/services/query";
import GlobalSetting from "@/services/globalsetting";

function CreateCustomertempHrpDialog({ dialog }) {
  const [dataLoaded, setDataLoaded] = useState(true);
  const [data, setData] = useState("");
  const [saveInProgress, setSaveInProgress] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const isCreateCustomertempEnabled = useState(true);

  useEffect(() => {
    let param={
        page: 1,
        pagesize: 5,
        code: 'HRP导入合同单位',
        type: '合同单位',
      }
    GlobalSetting.getlist(param).then(data => {
      const qid = Number(data.data[0].value);
      if(qid>0){
        Query.get({ id: qid }).then(results => {
          results.getQueryResultPromise().then(result => {
            setData(result.query_result.data.rows)
            });
          }).catch(error => {});
      }
    });
  }, []);

  const  handleSubmit=(record) => {
    setSaveInProgress(true);
    let data={id: 0,//
        userid: currentUser.id,//--操作员ID
        strcustomercode: record.STRCUSTOMERCODE,
        strcustomername: record.STRCUSTOMERNAME,
        representative: record.REPRESENTATIVE,
        mobile: record.MOBILE,
        address: record.ADDRESS,
        blnisinactive: true,}

    Customer.createcustomer(data).then(() => {
      setSaveInProgress(false);
      notification.success("添加成功.");
      })
      .catch(error => {
        notification.success("不能重复添加.");
        setSaveInProgress(false);
      });
  }
  const handleCancel =() =>{
    dialog.close();
  }
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div
        style={{
          padding: 8,
        }}
      >
        <Input
          ref={searchInput}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            筛选
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#1890ff' : undefined,
        }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (text) =>
        text
  });
  const listcolumns = [
    {
      title: '编码',
      key: 'STRCUSTOMERCODE',
      dataIndex: 'STRCUSTOMERCODE',
      ...getColumnSearchProps('STRCUSTOMERCODE'),
      sorter: (a, b) => a.STRCUSTOMERCODE.length - b.STRCUSTOMERCODE.length,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '名称',
      dataIndex: 'STRCUSTOMERNAME',
      key: 'STRCUSTOMERNAME',
      ...getColumnSearchProps('STRCUSTOMERNAME'),
      sorter: (a, b) => a.STRCUSTOMERNAME.length - b.STRCUSTOMERNAME.length,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '法定代表人',
      dataIndex: 'REPRESENTATIVE',
      key: 'REPRESENTATIVE',
    },
    {
      title: '电话',
      dataIndex: 'MOBILE',
      key: 'MOBILE',
    },
    {
      title: '地址',
      dataIndex: 'ADDRESS',
      key: 'ADDRESS',
    },
    {
      title: '操作',
      key: 'action',
      render: (record) => (
        <span>
           <a className="clickable" onClick={() => handleSubmit(record)}>添加</a>
        </span>
      ),
    },
  ];
  return (
    <ConfigProvider locale={zhCN}>
    <Modal
      {...dialog.props}
      // {...(isCreateCustomertempEnabled ? {} : { footer: null })}
      title="HRP单位"
      width={document.querySelector('body').offsetWidth*0.6}
      // okText="确认"
      // okButtonProps={{
      //   disabled: saveInProgress,
      //   loading: saveInProgress,
      //   "data-test": "DashboardSaveButton",
      // }}
      // cancelButtonProps={{
      //   display: 'none',
      // }}
      footer={[
        <Button key="back" onClick={handleCancel}>
          退出
        </Button>,
      ]}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateCustomertempHrpDialogExtra" disabled={!isCreateCustomertempEnabled}>
        <div>
            <Table rowKey='ID'
                  columns={listcolumns}
                  dataSource={data}
                  pagination={false}
            />
        </div>
      </DynamicComponent>
      )}
    </Modal></ConfigProvider>
  );
}

CreateCustomertempHrpDialog.propTypes = {
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateCustomertempHrpDialog);